package com.salton123.soulove.sailfish.video.ui.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import androidx.viewpager.widget.PagerAdapter
import com.salton123.soulove.app.R
import com.salton123.soulove.sailfish.db.VideoItem
import com.salton123.utils.ImageLoader
import java.util.ArrayList

class VideoPlayAdapterStyle : PagerAdapter() {
    /**
     * View缓存池，从ViewPager中移除的item将会存到这里面，用来复用
     */
    private val mViewPool: MutableList<View> = ArrayList()
    private val dataList: MutableList<VideoItem> = mutableListOf()

    fun setData(datas: MutableList<VideoItem>) {
        this.dataList.addAll(datas)
    }

    fun getData(): MutableList<VideoItem> {
        return dataList
    }

    fun getItem(position: Int): VideoItem? {
        if (position < dataList.size) {
            return dataList[position]
        }
        return null
    }

    override fun getCount(): Int {
        return dataList.size
    }

    override fun isViewFromObject(view: View, o: Any): Boolean {
        return view == o
    }

    override fun instantiateItem(container: ViewGroup, position: Int): Any {
        val context = container.context
        var view: View? = null
        if (mViewPool.size > 0) { //取第一个进行复用
            view = mViewPool[0]
            mViewPool.removeAt(0)
        }
        val viewHolder: ViewHolder
        if (view == null) {
            view = LayoutInflater.from(context).inflate(R.layout.adapter_item_video_play_style, container, false)
            viewHolder = ViewHolder(view)
        } else {
            viewHolder = view.tag as ViewHolder
        }
        val (filePath, _, name) = dataList[position]
        ImageLoader.loadImage(viewHolder.ivThumbnail, filePath)
        viewHolder.position = position
        container.addView(view)
        return view!!
    }

    override fun destroyItem(container: ViewGroup, position: Int, obj: Any) {
        val itemView = obj as View
        container.removeView(itemView)
        mViewPool.add(itemView)
    }

    fun removeItem(videoItem: VideoItem) {
        dataList.remove(videoItem)
        notifyDataSetChanged()
    }

    /**
     * 借鉴ListView item复用方法
     */
    internal class ViewHolder(itemView: View) {
        var position = 0
        var ivThumbnail: ImageView = itemView.findViewById(R.id.ivThumbnail)
        var flContainer: FrameLayout = itemView.findViewById(R.id.flContainer)

        init {
            itemView.tag = this
        }
    }
}